package server;
import java.util.*;
import msgs.*;

/**
 * This thread class runs when a user tries to disconnect
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class ClientRemover extends Thread implements TTConstants {
	private ClientMsg cmsg;
	
	public ClientRemover(ClientMsg cmsg) {
		this.cmsg = cmsg;
	}
	
	public void run() {
		// see if they're even logged on
		if (!(TTServer.connTable.containsKey(cmsg.getName()))) {
			cmsg.setResponse(Responses.DENY);
			ClientSender.outQ.add(cmsg);
			return;
		}
		
		// authenticate with key
		if (!(Arrays.equals(cmsg.getClientKey(), TTServer.connTable.get(cmsg.getName()).getClientKey()))) {
			cmsg.setResponse(Responses.DENY);
			ClientSender.outQ.add(cmsg);
			return;
		}
		
		// ok, they're legit.
		// notify everyone!
		if (TTServer.interestedIn.containsKey(cmsg.getName())) {
			ArrayList<String> al = (ArrayList<String>) TTServer.interestedIn.get(cmsg.getName());
			ClientMsg cm;
			for (String name : al) {
				if (TTServer.connTable.containsKey(name)) {
					cm = new ClientMsg(TTServer.connTable.get(name), TTConstants.Actions.OFFLINE_NOTICE);
					cm.setUser(cmsg.getName());
					ClientSender.outQ.add(cm);
				}
			}
		}
		
		
		//remove from conntable
		synchronized(TTConstants.lock) {
			TTServer.connTable.remove(cmsg.getName());
		}
	}
}
